package cn.wit.db.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.wit.db.entity.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class AuthSuccessHandler implements AuthenticationSuccessHandler {
	private static final Logger logger = LoggerFactory.getLogger(AuthSuccessHandler.class);

	@Autowired
	ObjectMapper mapper;
	
	@Autowired
	JwtTokenProvider jwtTokenProvider;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("登陆成功！{}", authentication.getPrincipal());

		// 登陆成功后，往响应头里面写入token
		jwtTokenProvider.insertAuthenticationToken(response, authentication);
	
		AjaxResult result = new AjaxResult(200, "登陆成功！");
		
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(mapper.writeValueAsString(result));
	}
}
